package com.mhl.campuscabinet;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.mhl.View.StaggeredDividerItemDecoration;
import com.mhl.adapter.ProductAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.Tag;
import com.mhl.entity.User;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TabFragment extends Fragment {

    private List<Product> productList = new ArrayList<>();
    //
    private List<Tag> TagList = LocalData.getInstance().TagList;
    private SmartRefreshLayout refreshLayout;
    private ProductAdapter adapter;
    private String title;
    private boolean flag = true;
    private Handler handler;
    private int old_account;

    // 加载方式
    private final static int INIT_LOAD = 0;
    private final static int REFRESH = 1;
    private final static int LOAD_MORE = 2;

    public TabFragment(String title) {
        this.title = title;
    }

    @Override
    public void onStart() {
        super.onStart();
//        flag = true;
        adapter.notifyDataSetChanged();
        System.out.println("你好，我是" + title);
    }



    @Override
    public void onResume() {
        super.onResume();
        if (flag) {
            flag = false;
            System.out.println("loaded product start");
            initProducts(title, INIT_LOAD);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab, container, false);

        MainActivity mainActivity = (MainActivity) getActivity();
        RecyclerView recyclerView = view.findViewById(R.id.recycle_view);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        // 解决重新分配高度的问题
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ProductAdapter(productList, mainActivity);
        recyclerView.setAdapter(adapter);
        refreshLayout = view.findViewById(R.id.smart_refresh);
        // 修改阻尼效果（0 - 1），越小阻尼越大，默认0.5
        refreshLayout.setDragRate(0.6f);
        // 设置主题颜色
        refreshLayout.setPrimaryColorsId(R.color.purple_200);
        // 设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(mainActivity).setEnableHorizontalDrag(true));
        // 设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new BallPulseFooter(mainActivity).setSpinnerStyle(SpinnerStyle.Scale));
        // 下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                refreshProduct(title);
            }
        });
        // 上拉加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                loadMoreProduct(title);
            }
        });
        // 加载视图
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case INIT_LOAD:{
                        adapter.notifyDataSetChanged();
                    }
                    break;
                    case REFRESH:{
                        adapter.notifyDataSetChanged();
                        refreshLayout.finishRefresh(true);
                    }
                    break;
                    case LOAD_MORE:{
                        try {
                            adapter.notifyItemRangeChanged(old_account - 1, productList.size() - old_account);
                        } catch (Exception e) {
                            System.out.println("数组越界");
                            e.printStackTrace();
                        }
                        refreshLayout.finishLoadMore(true);
                    }
                    break;
                    default:
                        break;
                }
            }
        };
        return view;
    }


    // 初始化首页推荐商品列表，再onCreate以及下拉刷新中调用
    private void initProducts(String tagName, int type) {
        System.out.println(title + "开始加载");
        productList.clear(); // 这句话保留在第一行，用于清空list用的
        loadProducts(tagName, type);
    }

    // 这里客户端需要修改
    // 推荐直接改这个函数
    // 用于向服务器发送获取新内容的请求
    // 服务器应该发送一个json数组，包含每个产品对象的name，图片url（七牛云服务器中的图片地址）以及
    // 产品的价格
    // 客户端在接收json后需要将每个对象组装成一个个的Product对象存放到productList中即可
    private void loadProducts(String tagName, int type) {
        // 这里涉及网络
        // 建议客户端二人看一下9.2的OkHttp
        // 研究一下回调函数
        // 解析json的也麻烦看一下吧，推荐使用GSON
        int tag_number = 9;
        JSONObject userJson = new JSONObject();
        System.out.println(title + "进入loadProducts函数");
        try {
            //找到title对应的id 当请求的参数
            for (int i = 0; i < TagList.size(); i++) {
                if (tagName.equals("recommend")) {
                    tag_number = 9;
                } else if (TagList.get(i).getName().equals(tagName)) {
                    tag_number = TagList.get(i).getTag_id();
                    System.out.println(title + " 2 tag number is    " + tag_number);
                }
            }
            if (tag_number != 9) {
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                userJson.put("tag", tag_number);
                //userJson.put("tag", 2);
                String json = userJson.toString();
                RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

                int finalTag_number = tag_number;
                OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "tag/get/merchandise", requestBody, new Callback() {
                    Handler h = handler;

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                        System.out.println(e);
                        System.out.println("onfailure");
                        System.out.println(title + "3 tag number is " + finalTag_number);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        System.out.println(title + "接收到服务器响应");
                        final String ItemsString = response.body().string();
                        try {
                            int state = 1;
                            try {
                                JSONObject errcodeJson = new JSONObject(ItemsString);
                                state = errcodeJson.getInt("errcode");
                            } catch (JSONException e) {
                                System.out.println("onresponse");
                                System.out.println(title + "4 tag number is " + finalTag_number);
                                e.printStackTrace();
                            }
                            //Looper.prepare();
                            if (state == 1) {
                                //Toast.makeText(getActivity(), "Can't find this tag", Toast.LENGTH_SHORT).show();
                            } else if (state == 2) {
                                //Toast.makeText(getActivity(), "key error", Toast.LENGTH_SHORT).show();
                            } else {
                                JSONObject itemsJson = new JSONObject(ItemsString);
                                JSONArray itemArray = itemsJson.getJSONArray("data");
                                for (int i = 0; i < itemArray.length(); i++) {
                                    JSONObject item = itemArray.getJSONObject(i);
                                    Product product = new Product();
                                    product.setPrice(item.getDouble("pre_price"));
                                    product.setName(item.getString("name"));
                                    JSONArray urls = item.getJSONArray("url_list");
                                    product.setURL(urls.getString(0));

                                    product.setId(item.getInt("id"));
                                    productList.add(product);
                                    System.out.println(title + " loaded product:");
                                    System.out.println("name:   " + product.getName());
                                    System.out.println("url!!!!!");
                                    System.out.println("url:   " + product.getURL());
                                    h.sendEmptyMessage(type);
                                }

                            }
                            //Looper.loop();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
            } else {
                tag_number = 2;
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                userJson.put("user_id", User.getInstance().getUserId());
                String json = userJson.toString();
                RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

                OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp2() + "merchandise/get_recommend_list", requestBody, new Callback() {

                    Handler h = handler;

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        final String ItemsString = response.body().string();
                        try {
                            int state = 1;
                            try {
                                JSONObject errcodeJson = new JSONObject(ItemsString);
                                state = errcodeJson.getInt("errcode");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Looper.prepare();
                            if (state == 1) {
                                Toast.makeText(getActivity(), "Can't find this tag", Toast.LENGTH_SHORT).show();
                            } else if (state == 2) {
                                Toast.makeText(getActivity(), "key error", Toast.LENGTH_SHORT).show();
                            } else {
                                JSONObject itemsJson = new JSONObject(ItemsString);
                                JSONArray itemArray = itemsJson.getJSONArray("data");
                                for (int i = 0; i < itemArray.length(); i++) {
                                    JSONObject item = itemArray.getJSONObject(i);
                                    Product product = new Product();
                                    product.setPrice(item.getDouble("pre_price"));
                                    product.setName(item.getString("name"));
                                    JSONArray urls = item.getJSONArray("url_list");
                                    product.setURL(urls.getString(0));
                                    product.setId(item.getInt("id"));
                                    productList.add(product);
                                    //test
                                    System.out.println("loaded product:");
                                    System.out.println("name:   " + product.getName());
                                    System.out.println("url!!!!!");
                                    System.out.println("url:   " + product.getURL());
                                    h.sendEmptyMessage(type);
                                }

                            }
                            Looper.loop();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 下拉刷新后调用，负责建立子线程以及更改UI
    private void refreshProduct(String tagName) {
        initProducts(tagName, REFRESH);
    }

    // 上拉加载后调用，负责建立子线程以及更改UI
    private void loadMoreProduct(String tagName) {
        old_account = productList.size();
        loadProducts(tagName, LOAD_MORE);
    }

    // 测试用例
    private void test() {
        System.out.println("哈哈哈哈哈哈");
        productList.clear();
        for (int i = 0; i < 7; i++) {
            Product product1 = new Product();
            product1.setName("1");
            product1.setPrice(200);
            product1.setURL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200208%2F281ed353179745369814955cb31b02f0.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642953563&t=0d19afab90e64e4e7f7bc0d0a775f27a");
            productList.add(product1);
            Product product2 = new Product();
            product2.setName("外星人电脑");
            product2.setPrice(40000);
            product2.setURL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp7.itc.cn%2Fq_70%2Fimages01%2F20210525%2Fa28b2807ad8f425198d51a69446711f4.jpeg&refer=http%3A%2F%2Fp7.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642985623&t=74a2f7f5df24fe7e1e9c528088283751");
            productList.add(product2);
        }
//        adapter.notifyItemRangeChanged(0, productList.size());
    }
}